import React, { Component } from 'react'
import {
  Card,
  Icon,
  List,
} from 'antd'

import { reqCategory } from '../../api'
import LinkButton from '../../components/LinkButton'
import { BASE_IMG_URL } from '../../utils/constants'

const Item = List.Item

// Product 的详情子路由组件
export default class ProductDetail extends Component {

  state = {
    cName1: '', // 一级分类名称
    cName2: '', // 二级分类名称
  }

  UNSAFE_componentWillMount () {
    const { state } = this.props.location
    if (!state && typeof(state) !== 'object') {
      this.props.history.replace('/product')
    }
  }

  async componentDidMount () {
    // 得到当前的分类 ID
    const { pCategoryId, categoryId } = this.props.location.state.product

    if (pCategoryId === '0') { // 一级分类下的商品
      const result = await reqCategory(categoryId)
      const cName1 = result.data.name
      this.setState({ cName1 })
    } else { // 二级分类下的商品
      // 一次性发送多个请求只有都成功了，才正常处理
      const results = await Promise.all([reqCategory(pCategoryId), reqCategory(categoryId)])
      const cName1 = results[0].data.name
      const cName2 = results[1].data.name
      this.setState({ cName1,cName2 })
    }
  }

  render () {
    // 读取携带过来的 state 数据
    const  { name, desc, price, imgs, detail } = this.props.location.state.product
    const { cName1, cName2 } = this.state

    const title = (
      <span>
        <LinkButton>
          <Icon
            type='arrow-left'
            style={{marginRight: 10, fontSize: 18}}
            onClick={() => this.props.history.goBack()}
          />
        </LinkButton>
        <span>商品详情</span>
      </span>
    )

    return (
      <Card title={title} className='product-detail'>
        <List>
          <Item>
            <span className='left'>商品名称: </span>
            <span>{ name }</span>
          </Item>
          <Item>
            <span className='left'>商品描述: </span>
            <span>{ desc }</span>
          </Item>
          <Item>
            <span className='left'>商品价格: </span>
            <span>{ price }</span>
          </Item>
          <Item>
            <span className='left'>所属分类: </span>
            <span>{ cName1 }  { cName2 ? ' ---> ' + cName2 : null}</span>
          </Item>
          <Item>
            <span className='left'>商品图片: </span>
            <span>
              {
                imgs.map((item, i) => (
                  <img
                    key={i}
                    className='product-img'
                    src={BASE_IMG_URL + item}
                    alt="img"/>
                ))
              }
            </span>
          </Item>
          <Item>
            <span className='left'>商品详情: </span>
            <span dangerouslySetInnerHTML={{__html: detail}}></span>
          </Item>
        </List>
      </Card>
    )
  }
}
